/**
 * 
 */
package cen5501c.client;

import java.util.*;
import java.io.*;

import cen5501c.common.*;
import cen5501c.common.DelayCmd.DelayStatistics;

/**
 * @author Jiangyan Xu
 * 
 */
public class Client {

	/**
	 * Entry point.
	 * 
	 * @param args
	 */
	static boolean showFlag = false;
	static String hostName = null;
	static Integer port = 3030;// the default port
	static String operation = null;

	public static void main(String[] args) {
		try {
			List<String> arguments = new ArrayList<String>(args.length);
			for (int i = 0; i < args.length; i++) {
				arguments.add(args[i]);
			}

			// set "v";
			if (arguments.get(0).equalsIgnoreCase("-v")) {
				showFlag = true;
				arguments.remove(0);// delete the "-v" option to maintain the
									// indices
			}
			if (showFlag == false) {
				File log = new File("network.log");
				PrintStream plog;
				try {
					plog = new PrintStream(log);
					System.setOut(plog);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}

			String[] address = arguments.get(0).split(":");
			hostName = address[0];
			if (address.length > 1)// has : and port
			{
				port = Integer.parseInt(address[1]);
			}
			arguments.remove(0);
			// System.err.println("hostname is
			// "+hostName+"port"+port.toString());
			operation = arguments.get(0).toUpperCase();
			arguments.remove(0);// remove operation, for CmdBase' fillarg
			if (operation.equals("LISTFILES"))
				listFiles(arguments, operation);
			else if (operation.equals("GETFILE"))
				getFile(arguments, operation);
			else if (operation.equals("GETDELAY"))
				getDelay(arguments, operation);
			else
				System.err.println("Invalid operation type.");
		} catch (P2PException pe) {
			System.err.print(pe.getMessage());
		} catch (Exception e) {
			System.err.println("<LOCALERROR: " + e.getMessage() + ">");
		}
	}

	private static void listFiles(List<String> arg, String op) throws Exception {
		ListFilesCmd cmd = (ListFilesCmd) CommandFactory.createCmd(op, arg);
		TransferManager tm = new TransferManager(hostName, port);
		tm.callServer(cmd);
	}

	private static void getFile(List<String> arg, String op) throws Exception {
		// System.out.println("getfile");
		try {// eclipse automatically set * to .classpath
			Integer.parseInt(arg.get(2));
		} catch (NumberFormatException nfe) {
			// System.err.print("get *"+arg.get(2));
			arg.set(2, "*");
		}
		GetFileCmd cmd = (GetFileCmd) CommandFactory.createCmd(op, arg);
		TransferManager tm = new TransferManager(hostName, port);
		CmdBase cmdf = tm.callServer(cmd);
		FileManager fm = new FileManager();
		fm.storeFileContent((FileContentCmd) cmdf);
	}

	private static void getDelay(List<String> arg, String op) throws Exception {
		// System.out.println("getdelay");
		TransferManager tm = new TransferManager(hostName, port);
		DelayStatistics ds = tm.getDelay();
		System.out.println(ds);
	}
}
